﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WebApiCoreDemo.Api.Filters
{
    public class CustomResourceFilterAttribute : Attribute, IResourceFilter
    {
        private static Dictionary<string, object> dict = new Dictionary<string, object>();

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            //实例化控制器之前先判断缓存中是否有数据
            string key = context.HttpContext.Request.Path.ToString();
            if (dict.ContainsKey(key))
            {
                //Result短路器
                context.Result = dict[key] as ObjectResult;
            }
            Console.WriteLine("this is CustomResourceFilterAttribute.OnResourceExecuting()");
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            //Action执行完毕后把数据放到缓存中
            string key = context.HttpContext.Request.Path.ToString();
            ObjectResult objectResult = context.Result as ObjectResult;
            dict[key] = objectResult;
            Console.WriteLine("this is CustomResourceFilterAttribute.OnResourceExecuted()");
        }
    }
}
